<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 pb-8">
    <!-- 现代简约风格移动端数据看板 -->
    <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 pb-8">

      <!-- 场站筛选工具栏 -->
      <div class="relative">
        <!-- 工具栏容器 -->
        <div class="px-4 pt-4 flex items-center justify-between">
          <!-- 场站筛选按钮 -->
          <div class="relative station-picker-container">
            <button @click="toggleStationPicker" class="station-picker-button inline-flex items-center gap-2 px-4 py-2 bg-white/90 backdrop-blur rounded-xl shadow-sm border border-gray-200 text-gray-700 hover:bg-white transition-all duration-200">
              <span class="font-medium truncate max-w-[120px]">{{ selectedStation ? selectedStation.name : '全部场站' }}</span>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-500">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
              </svg>
            </button>

            <!-- 场站选择弹窗 - 跟随按钮定位 -->
            <div v-if="showStationPicker" class="absolute top-full left-0 mt-1 z-50 w-80 max-w-sm bg-white rounded-2xl shadow-2xl border border-gray-200 overflow-hidden animate-slide-up" @click.stop>
              <!-- 搜索框 -->
              <div class="p-5 border-b border-gray-100">
                <div class="relative" @click.stop>
                  <input v-model="stationSearch" type="text" placeholder="搜索场站" class="w-full px-4 py-3 pl-12 bg-gray-50 rounded-lg text-base border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" @click.stop>
                  <svg class="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                  </svg>
                </div>
              </div>

              <!-- 场站列表 -->
              <div class="max-h-72 overflow-y-auto">
                <!-- 全部场站选项 -->
                <button @click="selectStation(null)" class="w-full px-5 py-4 text-left hover:bg-gray-50 border-b border-gray-100 transition-colors" :class="{'bg-blue-50 text-blue-600': !selectedStation}">
                  <div class="font-medium text-base">全部场站</div>
                </button>

                <!-- 场站列表 -->
                <button v-for="station in filteredStations" :key="station.id" @click="selectStation(station)"
                        class="w-full px-5 py-4 text-left hover:bg-gray-50 border-b border-gray-100 transition-colors last:border-b-0"
                        :class="{'bg-blue-50 text-blue-600': selectedStation?.id === station.id}">
                  <div class="font-medium text-base truncate">{{ station.name }}</div>
                </button>
              </div>
            </div>
          </div>

          <!-- 场站排名入口按钮 -->
          <button @click="goToRanking" class="inline-flex items-center gap-2 px-3 py-2 bg-blue-50 rounded-xl text-base font-semibold text-blue-600 hover:text-blue-700 hover:bg-blue-100 transition-all duration-200 border border-blue-200">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-7 h-7">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 13h4v8H3v-8Zm7-6h4v14h-4V7Zm7 3h4v11h-4V10Z"/>
            </svg>
            <span>场站排名</span>
          </button>
        </div>


      </div>

      <!-- 主要数据展示 -->
      <div class="px-3 pt-4">

        <!-- 总收入卡片 - 放大后的设计 -->
        <div class="relative overflow-hidden rounded-3xl bg-gradient-to-br from-blue-600 via-purple-600 to-indigo-700 text-white shadow-glass">

          <div class="p-4">
            <div class="flex items-center justify-between mb-6">
              <div>
                <div class="text-xl font-semibold text-white/90 tracking-wide">总收入</div>
                <div class="mt-3 text-4xl font-black tracking-tight">¥{{ formatNumber(currentData.totalRevenue) }}</div>
              </div>
              <!-- 今日昨日切换按钮 -->
              <div class="bg-white/20 backdrop-blur-md rounded-full p-1 flex items-center gap-1">
                <button @click="selectDate('today')" class="px-4 py-2 rounded-full text-base font-medium transition-all duration-200"
                        :class="selectedDate === 'today' ? 'bg-white text-blue-700 shadow-md' : 'text-white/90 hover:text-white'">今日</button>
                <button @click="selectDate('yesterday')" class="px-4 py-2 rounded-full text-base font-medium transition-all duration-200"
                        :class="selectedDate === 'yesterday' ? 'bg-white text-blue-700 shadow-md' : 'text-white/90 hover:text-white'">昨日</button>
              </div>
            </div>

            <!-- 四个数据卡片网格 -->
            <div class="mt-6 grid grid-cols-2 gap-3">
              <div class="rounded-2xl bg-white/18 backdrop-blur-sm p-3 border border-white/20">
                <div class="text-sm font-semibold text-white/85 tracking-wide mb-1">电费</div>
                <div class="text-lg font-bold truncate text-white">¥{{ formatNumber(currentData.electricityFee) }}</div>
              </div>
              <div class="rounded-2xl bg-white/18 backdrop-blur-sm p-3 border border-white/20">
                <div class="text-sm font-semibold text-white/85 tracking-wide mb-1">服务费</div>
                <div class="text-lg font-bold truncate text-white">¥{{ formatNumber(currentData.serviceFee) }}</div>
              </div>
              <div class="rounded-2xl bg-white/18 backdrop-blur-sm p-3 border border-white/20">
                <div class="text-sm font-semibold text-white/85 tracking-wide mb-1">订单数量</div>
                <div class="text-lg font-bold truncate text-white">{{ formatNumber(currentData.orderCount) }}</div>
              </div>
              <div class="rounded-2xl bg-white/18 backdrop-blur-sm p-3 border border-white/20">
                <div class="text-sm font-semibold text-white/85 tracking-wide mb-1">充电量</div>
                <div class="text-lg font-bold truncate text-white">{{ formatNumber(currentData.chargingAmount) }} kWh</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 实时监控卡片 -->
        <div class="mt-3 px-0">
          <div class="bg-white rounded-3xl shadow-lg p-3">
            <!-- 两列布局：实时枪位状态 - 异常订单记录 -->
            <div class="flex flex-row gap-3">

              <!-- 左侧：实时枪位状态 -->
              <div class="flex-1 bg-gray-50 rounded-2xl p-2.5 border border-gray-200">
                <div class="text-base font-semibold text-gray-700 mb-2.5 text-center">实时枪位状态</div>

                <!-- 枪位状态列 - 变矮版 -->
                <div class="space-y-1.5">
                  <!-- 空闲 -->
                  <div class="flex items-center justify-between p-2 bg-green-100 rounded-lg border border-green-200 h-12">
                    <div class="flex items-center gap-2">
                      <div class="w-2.5 h-2.5 rounded-full bg-green-500 shadow-sm"></div>
                      <span class="text-sm font-semibold text-gray-800">空闲</span>
                    </div>
                    <span class="text-lg font-bold text-green-700">24</span>
                  </div>

                  <!-- 充电中 -->
                  <div class="flex items-center justify-between p-2 bg-blue-100 rounded-lg border border-blue-200 h-12">
                    <div class="flex items-center gap-2">
                      <div class="w-2.5 h-2.5 rounded-full bg-blue-500 shadow-sm"></div>
                      <span class="text-sm font-semibold text-gray-800">充电中</span>
                    </div>
                    <span class="text-lg font-bold text-blue-700">16</span>
                  </div>

                  <!-- 占用 -->
                  <div class="flex items-center justify-between p-2 bg-yellow-100 rounded-lg border border-yellow-200 h-12">
                    <div class="flex items-center gap-2">
                      <div class="w-2.5 h-2.5 rounded-full bg-yellow-500 shadow-sm"></div>
                      <span class="text-sm font-semibold text-gray-800">占用</span>
                    </div>
                    <span class="text-lg font-bold text-yellow-700">8</span>
                  </div>

                  <!-- 故障 -->
                  <div class="flex items-center justify-between p-2 bg-red-100 rounded-lg border border-red-200 h-12">
                    <div class="flex items-center gap-2">
                      <div class="w-2.5 h-2.5 rounded-full bg-red-500 shadow-sm"></div>
                      <span class="text-sm font-semibold text-gray-800">故障</span>
                    </div>
                    <span class="text-lg font-bold text-red-700">3</span>
                  </div>

                  <!-- 离线 -->
                  <div class="flex items-center justify-between p-2 bg-gray-100 rounded-lg border border-gray-200 h-12">
                    <div class="flex items-center gap-2">
                      <div class="w-2.5 h-2.5 rounded-full bg-gray-500 shadow-sm"></div>
                      <span class="text-sm font-semibold text-gray-800">离线</span>
                    </div>
                    <span class="text-lg font-bold text-gray-700">5</span>
                  </div>
                </div>
              </div>

              <!-- 右侧：异常订单记录 -->
              <div class="flex-1 bg-gray-50 rounded-2xl p-2.5 border border-gray-200">
                <div class="text-base font-semibold text-gray-700 mb-2.5 text-center">异常订单记录</div>

                <!-- 异常订单列表 - 支持滑动 -->
                <div class="space-y-2 h-64 overflow-y-auto">
                  <!-- 订单1 -->
                  <div class="p-2.5 bg-red-100 rounded-lg border border-red-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-red-700 truncate">充电中断</span>
                      <span class="text-sm text-red-600 whitespace-nowrap">12:30</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">朝阳站-枪位A03</div>
                  </div>

                  <!-- 订单2 -->
                  <div class="p-2.5 bg-orange-100 rounded-lg border border-orange-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-orange-700 truncate">支付失败</span>
                      <span class="text-sm text-orange-600 whitespace-nowrap">11:45</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">浦东站-枪位B12</div>
                  </div>

                  <!-- 订单3 -->
                  <div class="p-2.5 bg-yellow-100 rounded-lg border border-yellow-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-yellow-700 truncate">通讯异常</span>
                      <span class="text-sm text-yellow-600 whitespace-nowrap">10:20</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">天河站-枪位C08</div>
                  </div>

                  <!-- 订单4 -->
                  <div class="p-2.5 bg-purple-100 rounded-lg border border-purple-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-purple-700 truncate">超时占用</span>
                      <span class="text-sm text-purple-600 whitespace-nowrap">09:15</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">南山站-枪位D05</div>
                  </div>

                  <!-- 更多订单示例 -->
                  <div class="p-2.5 bg-blue-100 rounded-lg border border-blue-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-blue-700 truncate">设备故障</span>
                      <span class="text-sm text-blue-600 whitespace-nowrap">08:10</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">北京站-枪位E01</div>
                  </div>

                  <div class="p-2.5 bg-green-100 rounded-lg border border-green-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-green-700 truncate">连接超时</span>
                      <span class="text-sm text-green-600 whitespace-nowrap">07:45</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">上海站-枪位F02</div>
                  </div>

                  <div class="p-2.5 bg-pink-100 rounded-lg border border-pink-200 h-16">
                    <div class="flex items-center justify-between">
                      <span class="text-base font-semibold text-pink-700 truncate">充电异常</span>
                      <span class="text-sm text-pink-600 whitespace-nowrap">06:30</span>
                    </div>
                    <div class="text-sm text-gray-600 truncate mt-1">广州站-枪位G03</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 经营日历、收入趋势、电量趋势切换卡片 -->
        <div class="mt-3 px-0">
          <div class="bg-white rounded-3xl shadow-lg border border-gray-100 overflow-visible">
            <!-- 顶部导航标签 -->
            <div class="px-3 py-3 border-b border-gray-100">
              <div class="flex items-center justify-center gap-3">
                <button @click="setTab('calendar')" :class="tabBtn('calendar')" class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-200">营收日历</button>
                <button @click="setTab('income')" :class="tabBtn('income')" class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-200">收入趋势</button>
                <button @click="setTab('power')" :class="tabBtn('power')" class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-200">电量趋势</button>
              </div>
            </div>

            <!-- 面板内容 -->
            <div class="p-3">
            <!-- 营收日历 -->
            <div v-if="navTab==='calendar'">
              <!-- 头部：年月与统计、月份切换 -->
              <div class="flex items-center justify-between mb-3 h-12">
                <div class="flex items-center gap-2">
                  <button @click="prevMonth" class="p-2 rounded-lg hover:bg-gray-100 text-gray-500 transition-colors" aria-label="上个月">
                    <svg viewBox="0 0 24 24" class="w-5 h-5"><path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
                  </button>
                  <div class="text-lg font-semibold text-gray-900">{{ monthTitle }}</div>
                  <button @click="nextMonth" class="p-2 rounded-lg hover:bg-gray-100 text-gray-500 transition-colors" aria-label="下个月">
                    <svg viewBox="0 0 24 24" class="w-5 h-5"><path fill="currentColor" d="M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg>
                  </button>
                </div>
                <div class="text-sm text-gray-600 text-center">
                  <div class="flex items-center justify-center gap-1">
                    <span class="text-gray-500">日均：</span>
                    <span class="text-gray-900 font-medium">{{ monthAvg }} 元</span>
                  </div>
                  <div class="flex items-center justify-center gap-1 mt-1">
                    <span class="text-gray-500">总计：</span>
                    <span class="text-gray-900 font-medium">{{ monthTotal }} 元</span>
                  </div>
                </div>
              </div>

              <!-- 表头（周一~周日） -->
              <div class="grid grid-cols-7 gap-1 text-base text-gray-400 mb-2">
                <div class="text-center">周一</div>
                <div class="text-center">周二</div>
                <div class="text-center">周三</div>
                <div class="text-center">周四</div>
                <div class="text-center">周五</div>
                <div class="text-center">周六</div>
                <div class="text-center">周日</div>
              </div>
                <!-- 月历网格 -->
                <div class="grid grid-cols-7 gap-1">
                  <button v-for="cell in monthGrid" :key="cell.key" :disabled="!cell.inMonth" @click="cell.inMonth && selectDay(cell.day)"
                          class="aspect-square rounded-lg p-1 relative border transition duration-150 ease-out transform disabled:opacity-50 overflow-hidden"
                          :class="cellClass(cell)">
                    <div class="w-full h-full grid place-items-center relative">
                      <div class="text-sm font-semibold" :class="cell.inMonth ? (selectedDay===cell.day ? 'text-blue-600 text-base font-bold' : 'text-gray-900') : 'text-gray-300'">
                        {{ cell.day || '' }}
                      </div>
                    </div>
                  </button>
                </div>

                <!-- 选中日期详情 -->
                <div class="mt-2 rounded-xl border border-gray-200 bg-gray-50 p-3">
                  <div class="text-center">
                    <div class="text-base font-semibold text-gray-900">{{ selectedDateTitle }}</div>
                    <div class="text-xs text-gray-500 mt-1">--按结算时间统计--</div>
                  </div>
                  <div class="mt-3 grid grid-cols-2 gap-3 text-sm">
                    <div class="rounded-lg bg-white border border-gray-200 p-3 flex flex-col items-center justify-center">
                      <div class="text-sm text-gray-500 text-center">电费</div>
                      <div class="mt-1 font-semibold text-gray-900">{{ fmt(selectedStats.actualIncome) }}</div>
                    </div>
                    <div class="rounded-lg bg-white border border-gray-200 p-3 flex flex-col items-center justify-center">
                      <div class="text-sm text-gray-500 text-center">服务费</div>
                      <div class="mt-1 font-semibold text-gray-900">{{ fmt(selectedStats.totalServiceFee) }}</div>
                    </div>
                    <div class="rounded-lg bg-white border border-gray-200 p-3 flex flex-col items-center justify-center">
                      <div class="text-sm text-gray-500 text-center">订单数量</div>
                      <div class="mt-1 font-semibold text-gray-900">{{ selectedStats.orders }}</div>
                    </div>
                    <div class="rounded-lg bg-white border border-gray-200 p-3 flex flex-col items-center justify-center">
                      <div class="text-sm text-gray-500 text-center">充电量</div>
                      <div class="mt-1 font-semibold text-gray-900">{{ selectedStats.chargingAmount }} kWh</div>
                    </div>
                  </div>
                </div>
              </div>

            <!-- 收入趋势 -->
            <div v-else-if="navTab==='income'">
              <div class="w-full">
                <!-- 趋势月份切换 -->
                <div class="mb-3 flex items-center justify-between gap-2 text-sm text-gray-700 h-12">
                  <div class="flex items-center gap-2">
                    <button @click="prevTrendMonth" class="p-2 rounded-lg hover:bg-gray-100 text-gray-500" aria-label="上个月">
                      <svg viewBox="0 0 24 24" class="w-5 h-5"><path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
                    </button>
                    <div class="text-lg font-semibold text-gray-900">{{ trendMonthTitle }}</div>
                    <button @click="nextTrendMonth" class="p-2 rounded-lg hover:bg-gray-100 text-gray-500" aria-label="下个月">
                      <svg viewBox="0 0 24 24" class="w-5 h-5"><path fill="currentColor" d="M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg>
                    </button>
                  </div>
                  <div class="text-xs text-gray-500 pr-1 select-none">单位：元</div>
                </div>
                <!-- 收入趋势图表 - ECharts版本 -->
                <div class="w-full h-96 bg-gradient-to-br from-blue-50 via-purple-50 to-indigo-50 rounded-2xl p-4 border border-blue-100 shadow-sm">
                  <!-- 图表容器 -->
                  <div ref="incomeChart" class="w-full h-full"></div>
                </div>
              </div>
            </div>

            <!-- 电量趋势 -->
            <div v-else-if="navTab==='power'">
              <div class="w-full">
                <!-- 趋势月份切换 -->
                <div class="mb-3 flex items-center justify-between gap-2 text-sm text-gray-700 h-12">
                  <div class="flex items-center gap-2">
                    <button @click="prevPowerMonth" class="p-2 rounded-lg hover:bg-gray-100 text-gray-500" aria-label="上个月">
                      <svg viewBox="0 0 24 24" class="w-5 h-5"><path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
                    </button>
                    <div class="text-lg font-semibold text-gray-900">{{ powerMonthTitle }}</div>
                    <button @click="nextPowerMonth" class="p-2 rounded-lg hover:bg-gray-100 text-gray-500" aria-label="下个月">
                      <svg viewBox="0 0 24 24" class="w-5 h-5"><path fill="currentColor" d="M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg>
                    </button>
                  </div>
                  <div class="text-xs text-gray-500 pr-1 select-none">单位：kWh</div>
                </div>
                <!-- 电量趋势图表 - 参考收入趋势的样式 -->
                <div class="w-full h-96 bg-gradient-to-br from-amber-50 via-orange-50 to-red-50 rounded-2xl p-4 border border-amber-100 shadow-sm">
                  <!-- 图表容器 -->
                  <div ref="powerChart" class="w-full h-full"></div>
                </div>
              </div>
            </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

const router = useRouter()

// 场站筛选相关
const showStationPicker = ref(false)
const stationSearch = ref('')
const selectedStation = ref(null)

// 模拟场站数据
const stations = ref([
  { id: 1, name: '北京朝阳充电站', address: '北京市朝阳区建国路88号' },
  { id: 2, name: '上海浦东充电站', address: '上海市浦东新区陆家嘴金融中心' },
  { id: 3, name: '广州天河充电站', address: '广州市天河区体育西路189号' },
  { id: 4, name: '深圳南山充电站', address: '深圳市南山区科技园南区' },
  { id: 5, name: '杭州西湖充电站', address: '杭州市西湖区文三路199号' },
  { id: 6, name: '成都武侯充电站', address: '成都市武侯区人民南路四段' },
  { id: 7, name: '重庆渝北充电站', address: '重庆市渝北区新牌坊一路' }
])

// 过滤后的场站列表
const filteredStations = computed(() => {
  if (!stationSearch.value.trim()) {
    return stations.value
  }
  const searchTerm = stationSearch.value.toLowerCase()
  return stations.value.filter(station =>
    station.name.toLowerCase().includes(searchTerm)
  )
})



// 跳转到排名页面
const goToRanking = () => {
  router.push('/ranking')
}

// 切换场站选择器显示状态
const toggleStationPicker = () => {
  showStationPicker.value = !showStationPicker.value
  if (showStationPicker.value) {
    stationSearch.value = ''
  }
}

// 选择场站
const selectStation = (station) => {
  selectedStation.value = station
  showStationPicker.value = false
  stationSearch.value = ''

  // 在这里可以添加根据选择的场站加载数据的逻辑
  console.log('选择的场站:', station ? station.name : '全部场站')
}

// 点击页面其他地方关闭弹窗
const handleClickOutside = (event) => {
  const button = document.querySelector('.station-picker-button')
  const picker = document.querySelector('.station-picker-container .absolute')

  if (button && picker && !button.contains(event.target) && !picker.contains(event.target)) {
    showStationPicker.value = false
  }
}

onMounted(() => {
  // 添加全局点击事件监听
  document.addEventListener('click', handleClickOutside)
})

// 实时数据生成器
const generateLiveData = () => {
  const baseRevenue = 12000 + Math.floor(Math.random() * 2000)
  const baseOrders = 200 + Math.floor(Math.random() * 80)

  return {
    totalRevenue: baseRevenue,
    electricityFee: Math.floor(baseRevenue * 0.65),
    serviceFee: Math.floor(baseRevenue * 0.18),
    otherFee: Math.floor(baseRevenue * 0.17),
    orderCount: baseOrders,
    chargingAmount: Math.floor(baseOrders * 22.5),
    chargingGrowth: (Math.random() * 20 - 5).toFixed(1),
    abnormalOrders: Math.floor(baseOrders * 0.03),
    abnormalGrowth: (Math.random() * 30 - 15).toFixed(1),
    members: 2400 + Math.floor(Math.random() * 200),
    memberGrowth: (Math.random() * 5).toFixed(1)
  }
}

// 模拟数据 - 带有动态变化
const todayData = ref(generateLiveData())
const yesterdayData = ref({
  totalRevenue: 11520,
  electricityFee: 7830,
  serviceFee: 2180,
  otherFee: 1510,
  orderCount: 216,
  chargingAmount: 4825,
  chargingGrowth: 8.2,
  abnormalOrders: 10,
  abnormalGrowth: 15,
  members: 2402,
  memberGrowth: 1.8
})

const selectedDate = ref('today')

// 计算当前显示的数据
const currentData = computed(() => {
  return selectedDate.value === 'today' ? todayData.value : yesterdayData.value
})

// 计算日期标签
const currentDateLabel = computed(() => {
  return selectedDate.value === 'today' ? '今日' : '昨日'
})

// 计算增长率
const growthRate = computed(() => {
  const today = todayData.value.totalRevenue
  const yesterday = yesterdayData.value.totalRevenue
  return ((today - yesterday) / yesterday * 100).toFixed(1)
})


// 选择日期
const selectDate = (date) => {
  selectedDate.value = date
}

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 经营日历、收入趋势、电量趋势功能
const navTab = ref('calendar')
const tabBtn = (k) => navTab.value === k ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700'
const setTab = (k) => {
  navTab.value = k
}

// 经营日历相关
const monthOffset = ref(0)
const targetDate = computed(() => {
  const d = new Date()
  d.setDate(1)
  d.setMonth(d.getMonth() + monthOffset.value)
  return d
})
const monthTitle = computed(() => `${targetDate.value.getFullYear()}年${targetDate.value.getMonth()+1}月`)
const daysInMonth = computed(() => new Date(targetDate.value.getFullYear(), targetDate.value.getMonth()+1, 0).getDate())
const firstDayWeek = computed(() => {
  const w = new Date(targetDate.value.getFullYear(), targetDate.value.getMonth(), 1).getDay()
  return (w === 0 ? 7 : w)
})

const monthTotal = computed(() => 12800 + monthOffset.value * 1000)
const monthAvg = computed(() => Math.round(monthTotal.value / daysInMonth.value))
const selectedDay = ref(1)

const monthGrid = computed(() => {
  const cells = []
  const lead = firstDayWeek.value - 1
  const totalCells = Math.ceil((lead + daysInMonth.value) / 7) * 7

  for (let i=0; i<totalCells; i++) {
    const day = i - lead + 1
    const inMonth = day >= 1 && day <= daysInMonth.value

    cells.push({
      key: `${monthTitle.value}-${i}`,
      day: inMonth ? day : '',
      inMonth
    })
  }
  return cells
})

const selectDay = (d) => {
  if (d && d >= 1 && d <= daysInMonth.value) {
    selectedDay.value = d
  }
}

const cellClass = (cell) => {
  if (!cell.inMonth) return 'bg-gray-50 text-gray-300 border-gray-100 cursor-default'

  const isSelected = selectedDay.value === cell.day

  if (isSelected) {
    return 'bg-blue-100 border-blue-300 ring-2 ring-blue-400 shadow-md scale-[1.02]'
  } else {
    return 'bg-white hover:bg-gray-50 border-gray-100 hover:shadow-sm'
  }
}

const selectedDateTitle = computed(() => `${targetDate.value.getFullYear()}年${targetDate.value.getMonth()+1}月${selectedDay.value}日`)
const selectedStats = computed(() => ({
  totalServiceFee: 6800,
  actualIncome: 12000,
  orders: 156,
  chargingAmount: 3510
}))

const prevMonth = () => {
  monthOffset.value -= 1
  selectedDay.value = 1
}
const nextMonth = () => {
  monthOffset.value += 1
  selectedDay.value = 1
}

const fmt = (n) => Number(n || 0).toFixed(2)

// 收入趋势相关
const trendMonthOffset = ref(0)
const trendTargetDate = computed(() => {
  const d = new Date()
  d.setDate(1)
  d.setMonth(d.getMonth() + trendMonthOffset.value)
  return d
})
const trendMonthTitle = computed(() => `${trendTargetDate.value.getFullYear()}年${trendTargetDate.value.getMonth()+1}月`)

// 收入趋势模拟数据
const trendData = computed(() => {
  // 基础数据生成器 - 模拟真实收入波动（生成每天的数据）
  const generateDailyData = (base, variance, daysInMonth, seasonality = 0) => {
    const data = []
    const baseVariance = variance * 0.3
    
    for (let day = 1; day <= daysInMonth; day++) {
      // 模拟周末效应（周六周日收入略低）
      const date = new Date(trendTargetDate.value.getFullYear(), trendTargetDate.value.getMonth(), day)
      const dayOfWeek = date.getDay()
      const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
      
      // 模拟月中收入偏高，月初和月底收入偏低
      const dayEffect = Math.sin((day - daysInMonth / 2) * Math.PI / daysInMonth) * 0.2
      
      // 季节效应
      const seasonEffect = seasonality * Math.sin(trendMonthOffset.value * Math.PI / 6) * 0.1
      
      // 随机波动（周末波动更大）
      const randomFactor = isWeekend ? Math.random() * baseVariance * 1.5 : Math.random() * baseVariance
      
      const dailyValue = base * (1 + dayEffect + seasonEffect) + randomFactor
      data.push(dailyValue)
    }
    
    return data
  }
  
  // 根据月份偏移量生成不同的数据模式
  const monthPattern = trendMonthOffset.value % 4
  let baseTotal, baseElectricity, baseService
  
  switch(monthPattern) {
    case 0: // 常规月份
      baseTotal = 12000
      baseElectricity = 7800
      baseService = 2400
      break
    case 1: // 旺季
      baseTotal = 14000
      baseElectricity = 9100
      baseService = 2800
      break
    case 2: // 淡季
      baseTotal = 10000
      baseElectricity = 6500
      baseService = 2000
      break
    case 3: // 增长期
      baseTotal = 13000
      baseElectricity = 8450
      baseService = 2600
      break
  }
  
  const daysInMonth = new Date(trendTargetDate.value.getFullYear(), trendTargetDate.value.getMonth() + 1, 0).getDate()
  
  // 生成每天的数据
  const totalRevenue = generateDailyData(baseTotal, 2000, daysInMonth, 500)
  const electricityFee = generateDailyData(baseElectricity, 1500, daysInMonth, 300)
  const serviceFee = generateDailyData(baseService, 500, daysInMonth, 200)
  
  return {
    totalRevenue: totalRevenue.map(val => Math.round(val)),
    electricityFee: electricityFee.map(val => Math.round(val)),
    serviceFee: serviceFee.map(val => Math.round(val)),
    // 添加统计数据用于显示
    monthMax: Math.max(...totalRevenue),
    monthMin: Math.min(...totalRevenue),
    monthAvg: Math.round(totalRevenue.reduce((a, b) => a + b, 0) / totalRevenue.length)
  }
})



const prevTrendMonth = () => { trendMonthOffset.value -= 1 }
const nextTrendMonth = () => { trendMonthOffset.value += 1 }

// 电量趋势相关
const powerMonthOffset = ref(0)
const powerTargetDate = computed(() => {
  const d = new Date()
  d.setDate(1)
  d.setMonth(d.getMonth() + powerMonthOffset.value)
  return d
})
const powerMonthTitle = computed(() => `${powerTargetDate.value.getFullYear()}年${powerTargetDate.value.getMonth()+1}月`)

const prevPowerMonth = () => { powerMonthOffset.value -= 1 }
const nextPowerMonth = () => { powerMonthOffset.value += 1 }

// 电量趋势模拟数据
const powerData = computed(() => {
  // 基础数据生成器 - 模拟电量消耗模式
  const generateDailyPowerData = (base, variance, daysInMonth, seasonality = 0) => {
    const data = []
    const baseVariance = variance * 0.3
    
    for (let day = 1; day <= daysInMonth; day++) {
      // 模拟工作日和周末的电量差异
      const date = new Date(powerTargetDate.value.getFullYear(), powerTargetDate.value.getMonth(), day)
      const dayOfWeek = date.getDay()
      const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
      
      // 模拟月中用电高峰，月初和月底用电较少
      const dayEffect = Math.sin((day - daysInMonth / 2) * Math.PI / daysInMonth) * 0.3
      
      // 季节效应
      const seasonEffect = seasonality * Math.sin(powerMonthOffset.value * Math.PI / 6) * 0.15
      
      // 随机波动（周末波动更大）
      const randomFactor = isWeekend ? Math.random() * baseVariance * 2 : Math.random() * baseVariance
      
      const dailyValue = base * (1 + dayEffect + seasonEffect) + randomFactor
      data.push(dailyValue)
    }
    
    return data
  }
  
  // 根据月份偏移量生成不同的用电模式
  const monthPattern = powerMonthOffset.value % 4
  let baseTotal, baseSharp, basePeak, baseFlat, baseValley
  
  switch(monthPattern) {
    case 0: // 常规月份
      baseTotal = 3500
      baseSharp = 800
      basePeak = 1200
      baseFlat = 900
      baseValley = 600
      break
    case 1: // 夏季用电高峰
      baseTotal = 4500
      baseSharp = 1000
      basePeak = 1500
      baseFlat = 1100
      baseValley = 900
      break
    case 2: // 淡季
      baseTotal = 2800
      baseSharp = 600
      basePeak = 900
      baseFlat = 700
      baseValley = 600
      break
    case 3: // 增长期
      baseTotal = 3800
      baseSharp = 850
      basePeak = 1300
      baseFlat = 950
      baseValley = 700
      break
  }
  
  const daysInMonth = new Date(powerTargetDate.value.getFullYear(), powerTargetDate.value.getMonth() + 1, 0).getDate()
  
  // 生成每天的电量数据 - 尖峰平谷模式
  const totalPower = generateDailyPowerData(baseTotal, 800, daysInMonth, 300)
  const sharpPower = generateDailyPowerData(baseSharp, 200, daysInMonth, 100)
  const peakPower = generateDailyPowerData(basePeak, 300, daysInMonth, 150)
  const flatPower = generateDailyPowerData(baseFlat, 250, daysInMonth, 120)
  const valleyPower = generateDailyPowerData(baseValley, 200, daysInMonth, 100)
  
  return {
    totalPower: totalPower.map(val => Math.round(val)),
    sharpPower: sharpPower.map(val => Math.round(val)),
    peakPower: peakPower.map(val => Math.round(val)),
    flatPower: flatPower.map(val => Math.round(val)),
    valleyPower: valleyPower.map(val => Math.round(val)),
    // 添加统计数据用于显示
    monthMax: Math.max(...totalPower),
    monthMin: Math.min(...totalPower),
    monthAvg: Math.round(totalPower.reduce((a, b) => a + b, 0) / totalPower.length)
  }
})

// ==========================
// ECharts图表模块 - 优化重构
// ==========================

const incomeChart = ref(null)
const powerChart = ref(null)
let chartInstance = null
let powerChartInstance = null

// 图表配置常量
const CHART_CONFIG = {
  // 动画配置
  animation: {
    enabled: true,
    duration: 1000,
    easing: 'cubicOut'
  },
  
  // 收入趋势颜色配置
  colors: {
    electricityFee: {
      gradient: [
        { offset: 0, color: '#3b82f6' },
        { offset: 1, color: '#1d4ed8' }
      ],
      emphasis: 'rgba(59, 130, 246, 0.5)'
    },
    serviceFee: {
      gradient: [
        { offset: 0, color: '#10b981' },
        { offset: 1, color: '#059669' }
      ],
      emphasis: 'rgba(16, 185, 129, 0.5)'
    },
    totalRevenue: {
      color: '#3b82f6',
      emphasis: 'rgba(59, 130, 246, 0.5)'
    }
  },
  
  // 电量趋势颜色配置
  powerColors: {
    peak: {
      gradient: [
        { offset: 0, color: '#f59e0b' },
        { offset: 1, color: '#d97706' }
      ],
      emphasis: 'rgba(245, 158, 11, 0.5)'
    },
    flat: {
      gradient: [
        { offset: 0, color: '#10b981' },
        { offset: 1, color: '#059669' }
      ],
      emphasis: 'rgba(16, 185, 129, 0.5)'
    },
    valley: {
      gradient: [
        { offset: 0, color: '#8b5cf6' },
        { offset: 1, color: '#7c3aed' }
      ],
      emphasis: 'rgba(139, 92, 246, 0.5)'
    },
    sharp: {
      gradient: [
        { offset: 0, color: '#ef4444' },
        { offset: 1, color: '#dc2626' }
      ],
      emphasis: 'rgba(239, 68, 68, 0.5)'
    },
    totalPower: {
      color: '#f59e0b',
      emphasis: 'rgba(245, 158, 11, 0.5)'
    }
  },
  
  // 布局配置
  grid: {
    left: '5%',
    right: '2%',
    bottom: '12%',
    top: '3%',
    containLabel: true
  },
  
  // 图例配置
  legend: {
    bottom: 0,
    left: 'center',
    textStyle: {
      color: '#374151',
      fontSize: 12
    },
    itemWidth: 14,
    itemHeight: 14,
    itemGap: 25
  }
}

// 工具函数：动态计算柱子宽度
const calculateBarWidth = (dataCount) => {
  const baseWidth = 60
  const minWidth = 60
  const maxWidth = 90
  
  if (dataCount <= 10) {
    return Math.min(maxWidth, baseWidth + (10 - dataCount) * 3)
  }
  
  return Math.max(minWidth, baseWidth - Math.max(0, (dataCount - 10) * 2))
}

// 工具函数：生成收入趋势tooltip内容
const generateTooltipContent = (params, trendData) => {
  let result = `<div style="font-weight: 600; margin-bottom: 12px; color: #111827; font-size: 14px; border-bottom: 1px solid #f3f4f6; padding-bottom: 8px;">${params[0].axisValue}</div>`
  
  // 总收入折线
  const totalIncome = trendData.value.totalRevenue[params[0].dataIndex]
  result += `
    <div style="display: flex; align-items: center; margin: 8px 0;">
      <span style="display: inline-block; width: 14px; height: 14px; background: #3b82f6; border: 2px solid white; box-shadow: 0 0 0 1px #3b82f6; margin-right: 10px; border-radius: 50%;"></span>
      <span style="flex: 1; font-weight: 500; padding-right: 15px;">总收入</span>
      <span style="font-weight: 600; color: #111827; font-size: 14px;">¥${formatNumber(totalIncome)}</span>
    </div>
  `
  
  // 堆叠柱形图数据
  params.forEach(item => {
    if (item.seriesType === 'bar') {
      const value = formatNumber(item.value)
      const name = item.seriesName
      
      const icon = name === '电费' 
        ? `<span style="display: inline-block; width: 14px; height: 14px; background: linear-gradient(180deg, #3b82f6 0%, #1d4ed8 100%); margin-right: 10px; border-radius: 3px;"></span>`
        : `<span style="display: inline-block; width: 14px; height: 14px; background: linear-gradient(180deg, #10b981 0%, #059669 100%); margin-right: 10px; border-radius: 3px;"></span>`
      
      result += `
        <div style="display: flex; align-items: center; margin: 8px 0;">
          ${icon}
          <span style="flex: 1; font-weight: 500; padding-right: 15px;">${name}</span>
          <span style="font-weight: 600; color: #111827; font-size: 14px;">¥${value}</span>
        </div>
      `
    }
  })
  
  return result
}

// 工具函数：生成电量趋势tooltip内容
const generatePowerTooltipContent = (params, powerData) => {
  let result = `<div style="font-weight: 600; margin-bottom: 12px; color: #111827; font-size: 14px; border-bottom: 1px solid #f3f4f6; padding-bottom: 8px;">${params[0].axisValue}</div>`
  
  // 总电量折线
  const totalPower = powerData.value.totalPower[params[0].dataIndex]
  result += `
    <div style="display: flex; align-items: center; margin: 8px 0;">
      <span style="display: inline-block; width: 14px; height: 14px; background: #f59e0b; border: 2px solid white; box-shadow: 0 0 0 1px #f59e0b; margin-right: 10px; border-radius: 50%;"></span>
      <span style="flex: 1; font-weight: 500; padding-right: 15px;">总</span>
      <span style="font-weight: 600; color: #111827; font-size: 14px;">${formatNumber(totalPower)} kWh</span>
    </div>
  `
  
  // 堆叠柱形图数据 - 尖峰平谷
  params.forEach(item => {
    if (item.seriesType === 'bar') {
      const value = formatNumber(item.value)
      const name = item.seriesName
      
      let icon = ''
      if (name === '尖') {
        icon = `<span style="display: inline-block; width: 14px; height: 14px; background: linear-gradient(180deg, #ef4444 0%, #dc2626 100%); margin-right: 10px; border-radius: 3px;"></span>`
      } else if (name === '峰') {
        icon = `<span style="display: inline-block; width: 14px; height: 14px; background: linear-gradient(180deg, #f59e0b 0%, #d97706 100%); margin-right: 10px; border-radius: 3px;"></span>`
      } else if (name === '平') {
        icon = `<span style="display: inline-block; width: 14px; height: 14px; background: linear-gradient(180deg, #10b981 0%, #059669 100%); margin-right: 10px; border-radius: 3px;"></span>`
      } else if (name === '谷') {
        icon = `<span style="display: inline-block; width: 14px; height: 14px; background: linear-gradient(180deg, #8b5cf6 0%, #7c3aed 100%); margin-right: 10px; border-radius: 3px;"></span>`
      }
      
      result += `
        <div style="display: flex; align-items: center; margin: 8px 0;">
          ${icon}
          <span style="flex: 1; font-weight: 500;">${name}</span>
          <span style="font-weight: 600; color: #111827; font-size: 14px;">${value} kWh</span>
        </div>
      `
    }
  })
  
  return result
}

// 工具函数：生成收入趋势图表配置选项
const generateChartOption = (trendData, dates) => {
  const barWidth = calculateBarWidth(dates.length) + '%'
  
  return {
    backgroundColor: 'transparent',
    animation: {
      enabled: CHART_CONFIG.animation.enabled,
      duration: CHART_CONFIG.animation.duration,
      easing: CHART_CONFIG.animation.easing
    },
    
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(255, 255, 255, 0.98)',
      borderColor: '#e5e7eb',
      borderWidth: 1,
      borderRadius: 8,
      padding: [12, 16],
      textStyle: {
        color: '#374151',
        fontSize: 13,
        lineHeight: 1.5
      },
      formatter: (params) => generateTooltipContent(params, trendData)
    },
    
    legend: {
      data: ['电费', '服务费', '总收入'],
      ...CHART_CONFIG.legend
    },
    
    grid: CHART_CONFIG.grid,
    
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#d1d5db',
          width: 2
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 11,
        fontWeight: '500'
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#9ca3af',
          width: 1
        },
        length: 4,
        alignWithLabel: true
      }
    },
    
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#d1d5db',
          width: 2
        }
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#9ca3af',
          width: 1
        },
        length: 4
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 11,
        fontWeight: '500',
        padding: [0, 12, 0, 0],
        formatter: (value) => formatNumber(value)
      }
    },
    
    dataZoom: [{
      type: 'inside',
      xAxisIndex: [0],
      start: 0,
      end: 100,
      minSpan: 10,
      maxSpan: 100,
      zoomLock: false,
      throttle: 100,
      filterMode: 'filter',
      moveOnMouseMove: true,
      preventDefaultMouseMove: false,
      zoomOnMouseWheel: true,
      moveOnMouseWheel: true,
      speed: 1,
      disabled: false
    }],
    
    series: [
      {
        name: '电费',
        type: 'bar',
        stack: 'income',
        barWidth,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, CHART_CONFIG.colors.electricityFee.gradient),
          borderRadius: 0
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.colors.electricityFee.emphasis
          }
        },
        data: trendData.value.electricityFee
      },
      {
        name: '服务费',
        type: 'bar',
        stack: 'income',
        barWidth,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, CHART_CONFIG.colors.serviceFee.gradient),
          borderRadius: 0
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.colors.serviceFee.emphasis
          }
        },
        data: trendData.value.serviceFee
      },
      {
        name: '总收入',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: CHART_CONFIG.colors.totalRevenue.color
        },
        itemStyle: {
          color: CHART_CONFIG.colors.totalRevenue.color,
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          lineStyle: {
            width: 4
          },
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.colors.totalRevenue.emphasis
          }
        },
        data: trendData.value.totalRevenue
      }
    ]
  }
}

// 工具函数：生成电量趋势图表配置选项
const generatePowerChartOption = (powerData, dates) => {
  const barWidth = calculateBarWidth(dates.length) + '%'
  
  return {
    backgroundColor: 'transparent',
    animation: {
      enabled: CHART_CONFIG.animation.enabled,
      duration: CHART_CONFIG.animation.duration,
      easing: CHART_CONFIG.animation.easing
    },
    
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(255, 255, 255, 0.98)',
      borderColor: '#e5e7eb',
      borderWidth: 1,
      borderRadius: 8,
      padding: [12, 16],
      textStyle: {
        color: '#374151',
        fontSize: 13,
        lineHeight: 1.5
      },
      formatter: (params) => generatePowerTooltipContent(params, powerData)
    },
    
    legend: {
      data: ['尖', '峰', '平', '谷', '总'],
      ...CHART_CONFIG.legend
    },
    
    grid: CHART_CONFIG.grid,
    
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#d1d5db',
          width: 2
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 11,
        fontWeight: '500'
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#9ca3af',
          width: 1
        },
        length: 4,
        alignWithLabel: true
      }
    },
    
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#d1d5db',
          width: 2
        }
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#9ca3af',
          width: 1
        },
        length: 4
      },
      splitLine: {
        lineStyle: {
          color: '#f3f4f6',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 11,
        fontWeight: '500',
        padding: [0, 12, 0, 0],
        formatter: (value) => formatNumber(value)
      }
    },
    
    dataZoom: [{
      type: 'inside',
      xAxisIndex: [0],
      start: 0,
      end: 100,
      minSpan: 10,
      maxSpan: 100,
      zoomLock: false,
      throttle: 100,
      filterMode: 'filter',
      moveOnMouseMove: true,
      preventDefaultMouseMove: false,
      zoomOnMouseWheel: true,
      moveOnMouseWheel: true,
      speed: 1,
      disabled: false
    }],
    
    series: [
      {
        name: '尖',
        type: 'bar',
        stack: 'power',
        barWidth,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, CHART_CONFIG.powerColors.sharp.gradient),
          borderRadius: 0
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.powerColors.sharp.emphasis
          }
        },
        data: powerData.value.sharpPower
      },
      {
        name: '峰',
        type: 'bar',
        stack: 'power',
        barWidth,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, CHART_CONFIG.powerColors.peak.gradient),
          borderRadius: 0
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.powerColors.peak.emphasis
          }
        },
        data: powerData.value.peakPower
      },
      {
        name: '平',
        type: 'bar',
        stack: 'power',
        barWidth,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, CHART_CONFIG.powerColors.flat.gradient),
          borderRadius: 0
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.powerColors.flat.emphasis
          }
        },
        data: powerData.value.flatPower
      },
      {
        name: '谷',
        type: 'bar',
        stack: 'power',
        barWidth,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, CHART_CONFIG.powerColors.valley.gradient),
          borderRadius: 0
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.powerColors.valley.emphasis
          }
        },
        data: powerData.value.valleyPower
      },
      {
        name: '总',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: CHART_CONFIG.powerColors.totalPower.color
        },
        itemStyle: {
          color: CHART_CONFIG.powerColors.totalPower.color,
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          lineStyle: {
            width: 4
          },
          itemStyle: {
            shadowBlur: 10,
            shadowColor: CHART_CONFIG.powerColors.totalPower.emphasis
          }
        },
        data: powerData.value.totalPower
      }
    ]
  }
}

// 核心方法：初始化收入趋势图表
const initChart = () => {
  if (!incomeChart.value) {
    console.warn('收入趋势图表容器未找到')
    return
  }
  
  try {
    chartInstance = echarts.init(incomeChart.value)
    updateChart()
    window.addEventListener('resize', handleResize)
  } catch (error) {
    console.error('收入趋势图表初始化失败:', error)
  }
}

// 核心方法：初始化电量趋势图表
const initPowerChart = () => {
  if (!powerChart.value) {
    console.warn('电量趋势图表容器未找到')
    return
  }
  
  try {
    powerChartInstance = echarts.init(powerChart.value)
    updatePowerChart()
    window.addEventListener('resize', handlePowerResize)
  } catch (error) {
    console.error('电量趋势图表初始化失败:', error)
  }
}

// 核心方法：更新收入趋势图表
const updateChart = () => {
  if (!chartInstance) {
    console.warn('收入趋势图表实例未初始化')
    return
  }
  
  try {
    const daysInMonth = new Date(trendTargetDate.value.getFullYear(), trendTargetDate.value.getMonth() + 1, 0).getDate()
    const dates = Array.from({length: daysInMonth}, (_, i) => `${i + 1}日`)
    
    const option = generateChartOption(trendData, dates)
    chartInstance.setOption(option, true)
  } catch (error) {
    console.error('收入趋势图表更新失败:', error)
  }
}

// 核心方法：更新电量趋势图表
const updatePowerChart = () => {
  if (!powerChartInstance) {
    console.warn('电量趋势图表实例未初始化')
    return
  }
  
  try {
    const daysInMonth = new Date(powerTargetDate.value.getFullYear(), powerTargetDate.value.getMonth() + 1, 0).getDate()
    const dates = Array.from({length: daysInMonth}, (_, i) => `${i + 1}日`)
    
    const option = generatePowerChartOption(powerData, dates)
    powerChartInstance.setOption(option, true)
  } catch (error) {
    console.error('电量趋势图表更新失败:', error)
  }
}

// 核心方法：处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

const handlePowerResize = () => {
  if (powerChartInstance) {
    powerChartInstance.resize()
  }
}

// 核心方法：清理资源
const cleanupChart = () => {
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('resize', handlePowerResize)
  
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  if (powerChartInstance) {
    powerChartInstance.dispose()
    powerChartInstance = null
  }
}

// 监听器：收入趋势数据变化监听
watch(trendData, () => {
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

// 监听器：电量趋势数据变化监听
watch(powerData, () => {
  nextTick(() => {
    updatePowerChart()
  })
}, { deep: true })

// 监听器：tab切换监听
watch(navTab, (newTab) => {
  nextTick(() => {
    if (newTab === 'income') {
      initChart()
    } else if (newTab === 'power') {
      initPowerChart()
    }
  })
})

// 生命周期钩子
onMounted(() => {
  // 延迟初始化以确保DOM渲染完成
  setTimeout(() => {
    if (navTab.value === 'income') {
      initChart()
    } else if (navTab.value === 'power') {
      initPowerChart()
    }
  }, 100)
})

onUnmounted(() => {
  cleanupChart()
})
</script>

<style scoped>
.bg-grad {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.shadow-glass {
  box-shadow:
    0 8px 32px 0 rgba(31, 38, 135, 0.37),
    0 2px 8px 0 rgba(31, 38, 135, 0.08),
    inset 0 1px 0 0 rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
}

/* 场站选择器动画 */
.animate-slide-up {
  animation: slideUp 0.2s ease-out forwards;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(-10px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 点击外部关闭弹窗的样式 */
.station-picker-container {
  position: relative;
}

.station-picker-button {
  cursor: pointer;
}
</style>
